package cn.wuxing.mediation.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.SecretKey;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class DESCrypt {

    // 密码/密钥
    private static String password = "DES-FYKJ-WZMZX-AJZ";
    public static void main(String[] args) {

        // 加密的十六进制字符串
        String encryptedHex = "516582E1A6BC0D40A503CA5CBB35152ADA916C7F01CC858CF2AD816B2B8F018D329A7AB6F21B396834539635B6BD638DDF6BDE4D367A1569767A47C4A4EB40D288E85E11BCB07B8F8A0C8894B42EE995EEB55C5013B04FF9D0954D17A5131C1517C77427A76C3335EDAEC5D7C997E13FD19B81C93B0BDF0BAD470FBD5E2B17C6345B71EFF09E379C36F100553B1E53C7743329246BD87EC40877A30FF731A46F414D02317560EEB0155C17DFCB0A630004DA3A14F00AC3D5AF28D8F100B5513066C6E654EC20F49165F99625243912058FA3AFC6E23F0B56C535F614333A97B56882D512ECF59897D27062EE07F95936A8E01EE190A33FDEEF64D30F112A7AD892E7957A7260CBFFF99144DBFE3A059D495EDE861AA12AF8AC51E8B6ECA1AC7CC898A81878D344B4B198577F5F9068278F3E8EE2C931C9D724F51F1EACC30844C2CB272AABE654482F7775C71051F3C5E10D8A255535F0F4E50DCDDC4576F56B72A56DAF8035FF3FA474B0A6D28E0C97541366F8867C12531B401E1F1BEF5C529F92C773109FCC6E9C0C85916BB7933C5065530097CDCC2C15C3DADCFD4E06A93E549DFF79D40EDE1DCD7E750D8E09A74DDF9C02D8E8936322802361B10DEC774113904E309F9CCD6DDB62131334747BC7BAAEED58699E95226542D31B2C8E186124E88BD735AC28C6177DA54AD97ACF06281544E9CE700C5DC278EC63774ADD1587D1607D26E68D85244548418895B4D783D12334BB033872CF4D1A77951A24";

        try {
            // 解密
            byte[] decrypted = decrypt(encryptedHex);
            System.out.println("解密结果: " + new String(decrypted, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] decrypt(String hexData) throws Exception {
        // 将十六进制字符串转换为字节数组
        byte[] encryptedData = hexStringToByteArray(hexData);

        // 截取前8个字节，生成合适的 DES 密钥
        byte[] keyBytes = new byte[8];
        System.arraycopy(password.getBytes("UTF-8"), 0, keyBytes, 0, Math.min(keyBytes.length, password.getBytes("UTF-8").length));

        SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");

        // 创建 Cipher 对象并初始化为解密模式
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);

        // 解密数据
        return cipher.doFinal(encryptedData);
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}